import * as userService from '@/services/user';

export default {
  namespace: 'user',
  state: {
    list: [],
    total: 0,
    pageNo: 1,
    pageSize: 5,
    roles: []
  },
  reducers: {
    setData(state, { payload }) {
      return { ...state, ...payload };
    },
  },
  effects: {
    *fetch({ payload: { pageNo } }, { call, put, select }) {
      const pageSize = yield select(state => state.user.pageSize);
      const response = yield call(userService.fetch, { pageNo, pageSize });
      if (response && typeof response.state !== undefined && response.state === 0) {
        yield put({ type: 'setData', payload: { ...response.data, pageNo} });
      } else {
        yield put({
          type: 'setData',
          payload: { list:[], total:0 },
        });
      }
    },
    *getAllRoles({ _ }, { call, put }) {
      const response = yield call(userService.getAllRoles);
      if (response && typeof response.state !== undefined && response.state === 0) {
        yield put({ type: 'setData', payload: { roles: response.data.roles } });
      } else {
        yield put({
          type: 'setData',
          payload: { roles:[] },
        });
      }
    },
    *add({ payload }, { call }) {
      return yield call(userService.add, payload);
    },
    *edit({ payload: { username, rest } }, { call }) {
      return yield call(userService.edit, username, rest);
    },
    *remove({ payload }, { call }) {
      return yield call(userService.remove, payload);
    },
  }
}
